package club.caihappy.service.impl;

import club.caihappy.domain.ResponseResult;
import club.caihappy.domain.entity.LoginUser;
import club.caihappy.domain.entity.User;
import club.caihappy.domain.vo.BlogUserLoginVO;
import club.caihappy.domain.vo.UserInfoVO;
import club.caihappy.service.BlogLoginService;
import club.caihappy.utils.BeanCopyUtils;
import club.caihappy.utils.JwtUtil;
import club.caihappy.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Created by DELL on 2022/11/2
 **/
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //用户身份认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断身份认证是否成功
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名密码错误");
        }
        //通过userid生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //将用户信息存入redis
        redisCache.setCacheObject("bloglogin:" + userId, loginUser);
        //bean拷贝将用户信息拷贝到userinfoVO
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVO.class);
        return ResponseResult.okResult(new BlogUserLoginVO(jwt, userInfoVO));
    }

    @Override
    public ResponseResult logout() {
        //获取token
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //解析出userid
        Long userId = loginUser.getUser().getId();
        //从redis中删除信息
        redisCache.deleteObject("bloglogin:" + userId);
        return ResponseResult.okResult();
    }
}
